package mysql

import (
	"fmt"
	"log"
	"os"
	"time"

	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
	"gorm.io/gorm/schema"

	"github.com/myblogs/models"
	"github.com/myblogs/settings"
)

var DB *gorm.DB

func Init() error {
	newLogger := logger.New(
		log.New(os.Stdout, "\r\n", log.LstdFlags), // io writer
		logger.Config{
			SlowThreshold:             time.Second,   // Slow SQL threshold
			LogLevel:                  logger.Silent, // Log level
			IgnoreRecordNotFoundError: true,          // Ignore ErrRecordNotFound error for logger
			ParameterizedQueries:      true,          // Don't include params in the SQL log
			Colorful:                  false,         // Disable color
		},
	)
	mysqlCon := settings.Config.MysqlConfig
	dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8mb4&parseTime=True&loc=Local",
		mysqlCon.Username,
		mysqlCon.Password,
		mysqlCon.Host,
		mysqlCon.Port,
		mysqlCon.DBName,
	)
	db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{
		NamingStrategy: schema.NamingStrategy{
			SingularTable: true,
		},
		Logger: newLogger,
	})
	if err != nil {
		return err
	}
	DB = db
	dbs, err := db.DB()
	if err != nil {
		return err
	}
	dbs.SetMaxOpenConns(100)
	dbs.SetMaxIdleConns(20)
	dbs.SetConnMaxLifetime(5 * time.Minute)
	DB.AutoMigrate(&models.Article{}, &models.Tags{})
	return nil
}
func Close() error {
	db, err := DB.DB()
	if err != nil {
		return err
	}
	return db.Close()
}
